package com.edward.puff.aop;

import com.edward.puff.config.PuffConfiguration;
import com.edward.puff.config.PuffMetadata;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * @Author: Edward
 * @Date: 2019/12/2 下午3:38
 * <p>
 * 拦截TransLogRepository方法,多数据源指定
 */
@Aspect
public class PuffRepositoryAspect {

    @Resource
    private PuffConfiguration puffConfig;

    @Around("target(com.edward.puff.repository.TransLogRepository)")
    public Object selectDataSourceIfMultiple(ProceedingJoinPoint joinPoint) {
        try {
            //获取对应元数据
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            PuffMetadata meta = puffConfig.getPuffMetadata(method.toGenericString());
            //指定数据源
            if (StringUtils.isNotEmpty(meta.getDateSourceName())) {
                //依赖多数据源实现 todo
//                DataSourceHolder.setCurrentDataSourceId(meta.getDateSourceName());
            }
            return joinPoint.proceed(joinPoint.getArgs());
        } catch (Throwable e) {
            throw new RuntimeException("aop selectDataSourceIfMultiple is fail", e);
        } finally {
//            DataSourceHolder.resetCurrentDataSourceId();
        }
    }

}
